package cn.wolfcode.shop.service;

import cn.wolfcode.shop.domain.UserInfo;
import cn.wolfcode.shop.domain.UserLogin;
import cn.wolfcode.shop.exception.UserException;
import cn.wolfcode.shop.mapper.UserInfoMapper;
import cn.wolfcode.shop.mapper.UserLoginMapper;
import cn.wolfcode.shop.util.MD5;
import cn.wolfcode.shop.util.RedisConstants;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service@Transactional
public class UserLoginServiceImpl implements IUserLoginService {
    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserLogin register(String username, String password) {
        int count = userLoginMapper.selectByUsername(username);
        if (count > 0) {
            throw new UserException("该用户名已经被注册");
        }
        UserLogin userLogin = new UserLogin();
        userLogin.setUserName(username);
        userLogin.setPassword(MD5.encode(password));
        userLoginMapper.insert(userLogin);
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userLogin.getId());
        userInfoMapper.insert(userInfo);
        return userLogin;
    }

    @Override
    public String login(String username, String password) {
        UserLogin userLogin = userLoginMapper.login(username, MD5.encode(password));
        if (userLogin == null) {
            throw new UserException("账号密码不匹配");
        }
        String token = createToken(userLogin);
        return token;
    }

    private String createToken(UserLogin userLogin) {
        String token = UUID.randomUUID().toString();
        String key = MessageFormat.format(RedisConstants.USER, token);
        redisTemplate.opsForValue().set(key, userLogin);
        redisTemplate.expire(key, 30, TimeUnit.DAYS);
        return token;
    }

    @Override
    public void logout(String token) {
        String key = MessageFormat.format(RedisConstants.USER, token);
        redisTemplate.delete(key);
    }
}
